<template>
  <div class="sub-categroy">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread></SubBread>
      <!-- 筛选区 -->
      <SubFilter @filter-change="filterChange"></SubFilter>
      <!-- 商品面板（排序+列表） -->
      <div class="goods-list">
      <SubSort @sort-change="sortChange"></SubSort>
      <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id" >
            <GoodsItem :goods="goods" />
          </li>
        </ul>
        <!-- 加载 -->
        <XtxInfiniteLoading @infinite="getDate" :loading="loading" :finished="finished" ></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: { SubBread, SubFilter, SubSort, GoodsItem },
  setup () {
    const route = useRoute()
    const loading = ref(false)
    const finished = ref(false)
    const goodsList = ref([]) // 商品数据
    let reqParams = { // 请求参数不必响应式
      page: 1,
      pageSize: 20
    }
    // 获取数据
    function getDate () {
      reqParams.categoryId = route.params.id
      loading.value = true // 开始加载要写在同步
      findSubCategoryGoods(reqParams).then(({ result }) => {
        if (result.items.length === reqParams.pageSize) {
          goodsList.value.push(...result.items)
          reqParams.page++
        } else if (result.items.length) { // 最后一页
          goodsList.value.push(...result.items)
          finished.value = true
        } else { // 万一最后一页刚好满溢
          finished.value = true
        }
        loading.value = false // 结束加载要写在异步内
      })
    }
    watch(() => route.params.id, (newVal) => {
      if (newVal && `/category/sub/${newVal}` === route.path) {
        finished.value = false
        goodsList.value = []
        reqParams.page = 1
        getDate()
      }
    }, { immediate: true })
    // 渲染排序结果
    function sortChange (sortParams) {
      finished.value = false
      goodsList.value = []
      reqParams = { ...reqParams, ...sortParams }
      reqParams.page = 1
    }
    // 渲染筛选结果
    function filterChange (filterParams) {
      finished.value = false
      goodsList.value = []
      reqParams = { ...reqParams, ...filterParams }
      reqParams.page = 1
    }

    return { getDate, loading, finished, goodsList, sortChange, filterChange }
  }
}
</script>

<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
    ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
